package com.tsugun.mediaplayer.view.fragment;

import android.content.Context;
import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.transition.TransitionInflater;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.tsugun.mediaplayer.R;
import com.tsugun.mediaplayer.model.entity.MusicModel;
import com.tsugun.mediaplayer.model.entity.SheetModel;
import com.tsugun.mediaplayer.presenter.provider.ListProvider;
import com.tsugun.mediaplayer.presenter.utils.SettingPreferenceHelper;
import com.tsugun.mediaplayer.presenter.utils.SystemHelper;
import com.tsugun.mediaplayer.view.activity.IndexActivity;
import com.tsugun.mediaplayer.view.adapter.MusicItemAdapter;
import com.tsugun.mediaplayer.view.adapter.MusicMenuAdapter;
import com.tsugun.mediaplayer.view.adapter.SheetItemMenuAdapter;
import com.tsugun.mediaplayer.view.loader.MediaImageLoad;
import com.tsugun.mediaplayer.view.widget.MusicMenuDialog;
import com.tsugun.mediaplayer.view.widget.SlidingRelativeLayout;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 专辑界面
 * Created by shize on 2017/4/20.
 */

public class AlbumFragment extends BaseFragment implements MusicMenuAdapter.OnMenuItemClickListener,
        AppBarLayout.OnOffsetChangedListener {

    public static final String INTENT_STRING_ALBUM_TITLE = "com.TsuGun.MediaPlayer.intent.album.title";

    @BindView(R.id.id_sliding_body)
    SlidingRelativeLayout mSlidingLayout;
    @BindView(R.id.id_bg_night)
    RelativeLayout mBgLayout;
    @BindView(R.id.id_album_app_bar)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.id_album_collapsing)
    CollapsingToolbarLayout mCollapsing;
    @BindView(R.id.id_album_image)
    ImageView mIvHead;
    @BindView(R.id.id_album_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.id_album_recycler)
    RecyclerView mRvList;
    @BindView(R.id.id_album_scroll_view)
    ScrollView mScrollView;
    @BindView(R.id.id_album_rl_load)
    RelativeLayout mRlLoad;
    @BindView(R.id.id_album_rl_nothing)
    RelativeLayout mRlNoting;
    @BindView(R.id.id_album_fab)
    FloatingActionButton mFab;
    @BindView(R.id.id_album_name)
    TextView mTvName;
    @BindView(R.id.id_album_artist)
    TextView mTvArtist;
    @BindView(R.id.id_album_count)
    TextView mTvCount;
    @BindView(R.id.id_album_desc_bar)
    RelativeLayout mRlDesc;

    private View mFragment;
    private Context mContext;
    private IndexActivity indexActivity;

    private ListProvider mProvider;
    private String mAlbumTitle;
    private List<MusicModel> mAlbumMusics;
    private MusicItemAdapter mMusicItemAdapter;
    private Unbinder unbinder;

    private int mPosition; // 当前点击菜单的位置
    private List<String> mMenuList; // 菜单列表项目
    private MusicMenuAdapter mMenuAdapter; // 菜单适配器
    private String mArtist; // 歌手菜单项前缀
    private String mAlbum; // 专辑菜单项前缀
    private MusicMenuDialog mDialog; // 菜单会话框
    private String mTitle; // 歌曲标题
    private List<SheetModel> mSheets; // 歌单列表

    private SheetItemMenuAdapter mSheetAdapter;
    private MusicMenuDialog mSheetDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTransition();
    }

    private void setTransition() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(
                android.R.transition.move));
        setSharedElementReturnTransition(TransitionInflater.from(getContext()).inflateTransition(
                android.R.transition.move));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mFragment = inflater.inflate(R.layout.fragment_album, container, false);
        mContext = container.getContext();
        unbinder = ButterKnife.bind(this, mFragment);

        initData();
        bindData();
        return mFragment;
    }

    /**
     * 初始化数据
     */
    private void initData() {
        indexActivity = (IndexActivity) mContext;
        mProvider = indexActivity.getListProvider();
        mAlbumTitle = getArguments().getString(INTENT_STRING_ALBUM_TITLE);
        mAlbumMusics = new ArrayList<>();
        mAlbumMusics.addAll((Collection<? extends MusicModel>) mProvider.getMusicByAlbum(mAlbumTitle));
        initLocalMusicMenu();
    }

    /**
     * 初始化本地歌曲菜单dialog数据
     */
    private void initLocalMusicMenu() {
        mArtist = getString(R.string.str_menu_item_artist);
        mAlbum = getString(R.string.str_menu_item_album);
        // 当前点击位置
        mPosition = 0;
        // 菜单项目标题
        mMenuList = new ArrayList<>();
        Collections.addAll(mMenuList, getResources().getStringArray(R.array.menu_item_title_list));
        // 图标
        int[] mIcons = new int[]{R.drawable.ic_menu_item_next, R.drawable.ic_menu_item_collection,
                R.drawable.ic_menu_item_artist, R.drawable.ic_menu_item_album,
                R.drawable.ic_menu_item_details, R.drawable.ic_menu_item_delete};
        mMenuAdapter = new MusicMenuAdapter(mContext, mMenuList, mIcons);
        mMenuAdapter.setOnMenuClickListener(this);
    }

    @Override
    public void onMenuClick(int pos) {
        // 菜单项点击事件
        switch (pos) {
            case MENU_ITEM_NEXT_PLAY:
                indexActivity.setNextPlayMusic(mAlbumMusics.get(mPosition).getId());
                break;
            case MENU_ITEM_COLLECTION:
                showSheetList();
                break;
            case MENU_ITEM_ARTIST:
                startArtistFragment(mAlbumMusics.get(mPosition).getArtist(), indexActivity);
                break;
            case MENU_ITEM_ALBUM:
                break;
            case MENU_ITEM_INFO:
                showMusicInfoDialog(mAlbumMusics.get(mPosition), mContext);
                break;
            case MENU_ITEM_DELETE:
                showDeleteAlertDialog(mContext);
                break;
        }
        mDialog.dismiss();
    }

    /**
     * 添加音乐到歌单
     */
    private void addMusicToSheet(int position) {
        SheetModel oldSheet = mSheets.get(position);
        List<String> strId = oldSheet.getMusicIdList();
        String sheetId = mAlbumMusics.get(mPosition).getId();
        if (strId.contains(sheetId)) {
            Snackbar.make(mRvList, R.string.str_duplicate_music, Snackbar.LENGTH_LONG).show();
            return;
        }
        strId.add(sheetId);
        mProvider.editSheetAddMusic(oldSheet, strId);
        mSheets.remove(oldSheet);
        oldSheet.setMusicIdList(strId);
        mSheets.add(oldSheet);
        // 更新歌单列表
        indexActivity.updateSheetList();
        Snackbar.make(mRvList, R.string.str_add_complete, Snackbar.LENGTH_LONG).show();
    }

    /**
     * 显示歌单会话框
     */
    private void showSheetList() {
        mTitle = getString(R.string.str_music) + mAlbumMusics.get(mPosition).getTitle();
        mSheets = new ArrayList<>();
        mSheets.addAll((Collection<? extends SheetModel>) mProvider.getSheet());
        mSheetAdapter = new SheetItemMenuAdapter(mContext, mSheets);
        mSheetAdapter.setProvider(mProvider);
        mSheetAdapter.setOnSheetItemClickListener(new SheetItemMenuAdapter.OnSheetItemClickListener() {
            @Override
            public void onItemClick(int position) {
                mSheetDialog.dismiss();
                addMusicToSheet(position);
            }
        });
        MusicMenuDialog.Builder builder = new MusicMenuDialog.Builder(mContext, mSheetAdapter, mTitle);
        mSheetDialog = builder.create();
        mSheetDialog.show();
    }

    @Override
    protected void deleteMusic() {
        mAlbumMusics.remove(mPosition);
        mMusicItemAdapter.notifyDataSetChanged();
    }

    /**
     * 绑定数据到控件
     */
    private void bindData() {
        bindSliding();
        initAlbumImage();
        mCollapsing.setTitle(mAlbumTitle);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                indexActivity.getMusicFragmentManager().backFragment();
            }
        });
        setLoadList();
        loadList();
        bindFab();
    }

    private void bindSliding() {
        mSlidingLayout.setOnSlidingListener(new SlidingRelativeLayout.OnSlidingListener() {
            @Override
            public void onDown() {

            }

            @Override
            public void onAnimationEnd(boolean isClose) {
                if (isClose){
                    indexActivity.getMusicFragmentManager().backFragment();
                }
            }
        });
    }

    /**
     * 绑定悬浮按钮
     */
    private void bindFab() {
        mFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                indexActivity.playMusicList(mAlbumMusics);
            }
        });
    }

    @Override
    protected void setSettingTheme() {
        // 设置主题
        int themeColor = indexActivity.getThemeColor();
        mFab.setBackgroundTintList(new ColorStateList(new int[][]{new int[0]}, new int[]{themeColor}));
        mCollapsing.setContentScrimColor(themeColor);
        mBgLayout.setBackgroundColor(SettingPreferenceHelper.INSTANCE.getBACKGROUND_COLOR());
    }

    /**
     * 初始化图片
     */
    private void initAlbumImage() {
        // 设置desc的信息
        String strCount = mAlbumMusics.size() + getString(R.string.str_count_music);
        mTvName.setText(mAlbumTitle);
        mTvArtist.setText(mAlbumMusics.get(0).getArtist());
        mTvCount.setText(strCount);
        // 设置可滚动控件的数据
        ViewGroup.LayoutParams lp = mAppBarLayout.getLayoutParams();
        int size = SystemHelper.INSTANCE.getScreensWidth(indexActivity);
        lp.height = size;
        lp.width = size;
        mAppBarLayout.setLayoutParams(lp);
        mAppBarLayout.addOnOffsetChangedListener(this);
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        // 划到顶部再显示title
        if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
            mCollapsing.setTitleEnabled(true);
        } else {
            mCollapsing.setTitleEnabled(false);
        }
    }

    /**
     * 设置显示正在加载列表
     */
    private void setLoadList() {
        mRvList.setVisibility(View.GONE);
        mRlLoad.setVisibility(View.VISIBLE);
    }

    /**
     * 加载列表
     */
    private void loadList() {
        List<MusicModel> musicList = (List<MusicModel>) mProvider.getMusicByAlbum(mAlbumTitle);
        mRlLoad.setVisibility(View.GONE);
        if (musicList.size() > 0) {
            initList(musicList);
            return;
        }
        setEmptyList();
    }

    /**
     * 初始化专辑歌曲列表
     */
    private void initList(final List<MusicModel> musicList) {
        mRvList.setVisibility(View.VISIBLE);
        MediaImageLoad.localImageLoad(musicList.get(0), mIvHead);
        mMusicItemAdapter = new MusicItemAdapter(mContext, musicList);
        mMusicItemAdapter.setOnMusicItemClickListener(new MusicItemAdapter.OnMusicItemClickListener() {
            @Override
            public void onItemClick(int position) {
                indexActivity.playMusicList(musicList, musicList.get(position).getId());
            }

            @Override
            public void onMenuClick(int position) {
                mPosition = position;
                showMenu(musicList);
            }
        });
        mRvList.setAdapter(mMusicItemAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mRvList.startLayoutAnimation();
        setSettingTheme(mRvList);
        indexActivity.setAdapter(mMusicItemAdapter);
    }

    /**
     * 显示歌曲菜单
     */
    private void showMenu(List<MusicModel> mResult) {
        String title = getString(R.string.str_music) + mResult.get(mPosition).getTitle();
        // 初始化菜单项目歌手和专辑显示
        mMenuList.remove(MENU_ITEM_ARTIST);
        mMenuList.add(MENU_ITEM_ARTIST, mArtist + mResult.get(mPosition).getArtist());
        mMenuList.remove(MENU_ITEM_ALBUM);
        mMenuList.add(MENU_ITEM_ALBUM, mAlbum + mResult.get(mPosition).getAlbum());
        MusicMenuDialog.Builder builder = new MusicMenuDialog.Builder(mContext, mMenuAdapter
                , title);
        mDialog = builder.create();
        mDialog.show();
    }

    /**
     * 设置空的列表提示
     */
    private void setEmptyList() {
        mScrollView.setVisibility(View.VISIBLE);
        mRlNoting.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
